//
//  PersonalInformationViewController.swift
//  IDF
//
//  Created by 陈徐挺 on 27/03/2018.
//  Copyright © 2018 Jesse.chen. All rights reserved.
//

import UIKit
import PromiseKit
import SwiftyJSON
import EasyPeasy
import BEMCheckBox
import SVProgressHUD
import SwiftyTimer

class InformationConfirmationViewController: BaseViewController {

    let formData = [
        ["title": "Name of bank"],
        ["title": "Bank account"],
        ["title": "Branch"],
        ["title": "Account"],
    ]

    @IBOutlet weak var label_1: UILabel!
    @IBOutlet weak var label_2: UILabel!
    @IBOutlet weak var label_3: UILabel!
    @IBOutlet weak var saveButtonView: FooterButtonView!
    @IBOutlet weak var baseTableView: UITableView!

    var bankInfo: BankInfo!
    var loanPurpose: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = "Information confirmation"
        label_1.text = "Rp \(Int(debitStyleModel.debitMoney!))"
        label_2.text = "\(debitStyleModel.debitPeriod!) Days"
        label_3.text = "Rp\(Int(debitStyleModel.payBackMoney!))"
        baseTableView.register(cellType: InputTableViewCell.self)
        baseTableView.tableFooterView = UIView()
        saveButtonView.doneButton.setTitle("Submit applications", for: .normal)
        saveButtonView.doneButton.setBlockFor(.touchUpInside) { [weak self] (button) in
            let _ = self?.bankInfo.save().then { _ -> Void in
                let _ = appUser.getBankInfo().then { obj -> Void in
                    if let this = self {
                        let dic: [String: Any] = [
                            "debitMoney": debitStyleModel.debitMoney!,
                            "debitPeriod": debitStyleModel.debitPeriod!,
                            "bankId": obj.bankId!,
                            "description": this.loanPurpose,
                        ]
                        SVProgressHUD.show()
                        Timer.after(0.5, {
                            let request = RequestData(path: "Debit/SubmitDebitRequest", param: dic)
                            let _ = netRequest(request).then { json -> Void in
                                let submittedView = SubmittedView(frame: appWindow.bounds)
                                appWindow.addSubview(submittedView)
                            }
                        })
                    }
                }

            }
        }
        saveButtonView.doneButton.alpha = 0.4
        saveButtonView.doneButton.isEnabled = false
        let footView = getFootView()
        baseTableView.addSubview(footView)
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return super.tableView(tableView, viewForHeaderInSection: section)
    }

    func saveData(_ tf: UITextField) {

        switch tf.tag {
        case 0:
            bankInfo.bankName = tf.text!
        case 1:
            bankInfo.bankCode = tf.text!
        case 2:
            bankInfo.subBankName = tf.text!
        case 3:
            bankInfo.contactName = tf.text!
        default:
            break
        }

    }
    @IBAction func infoClick(_ sender: UIButton) {
        let loanfeesView = LoanfeesView(frame: appWindow.bounds)
        loanfeesView.label_1.text = "Rp \(Int(debitStyleModel.debitMoney!))"
        loanfeesView.label_2.text = "Rp \(debitStyleModel.debitFee!)"
        loanfeesView.label_3.text = "\(debitStyleModel.debitPeriod!)"
        loanfeesView.label_4.text = "Rp \(Int(debitStyleModel.payBackMoney!))"
        loanfeesView.label_9.text = "overdue daily fee Rp \(Int(debitStyleModel.overdueDayInterest!))"
        loanfeesView.label_5.removeFromSuperview()
        loanfeesView.label_6.removeFromSuperview()
        loanfeesView.label_7.removeFromSuperview()
        loanfeesView.label_8.removeFromSuperview()
        loanfeesView.viewHeight.constant = 250
        
        appWindow.addSubview(loanfeesView)
        
    }
    
    func getFootView() -> UIView {
        let view = UIView(frame: CGRect(x: 0, y: 304, width: kWidth, height: 40))
        let label = UILabel()
        let checkBox = BEMCheckBox(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
        label.font = UIFont.systemFont(ofSize: 14)
        label.textColor = UIColor(hexString: "#666666")
        label.text = "I agree with the loan agreement"
        view.addSubview(label)
        view.addSubview(checkBox)
        view.backgroundColor = UIColor(hexString: "#F5F5F5")
        checkBox.boxType = .square
        checkBox.onAnimationType = .fill
        checkBox.offAnimationType = .fill
        checkBox.lineWidth = 2
        checkBox.onFillColor = UIColor(hexString: "8cadf5")!
        checkBox.onTintColor = UIColor(hexString: "8cadf5")!
        checkBox.onCheckColor = .white
        checkBox.delegate = self
        checkBox <- [
            Left(15).to(view, .left),
            CenterY()
        ]
        label <- [
            Left(45).to(view, .left),
            CenterY()
        ]
        return view
    }

    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */

}
extension InformationConfirmationViewController: UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, BEMCheckBoxDelegate {


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return formData.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: InputTableViewCell = tableView.dequeueReusableCell(for: indexPath)
        cell.fieldLabel.text = formData[indexPath.row]["title"]
        cell.fieldTF.text = ""
        cell.fieldTF.delegate = self
        cell.fieldTF.tag = indexPath.row
        cell.accessoryType = .none
        switch indexPath.row {
        case 0:
            cell.fieldTF.text = bankInfo.bankName
        case 1:
            cell.fieldTF.text = bankInfo.bankCode
        case 2:
            cell.fieldTF.text = bankInfo.subBankName
        case 3:
            cell.fieldTF.text = bankInfo.contactName
        default:
            break
        }
        tableView.contentSize = CGSize(width: 0, height: 360)
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let cell = tableView.cellForRow(at: indexPath) as! InputTableViewCell
        cell.fieldTF.becomeFirstResponder()
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 66
    }

    func didTap(_ checkBox: BEMCheckBox) {
        dPrint(checkBox.on)
        if checkBox.on {
            saveButtonView.doneButton.alpha = 1
            saveButtonView.doneButton.isEnabled = true
        } else {
            saveButtonView.doneButton.alpha = 0.4
            saveButtonView.doneButton.isEnabled = false
        }
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "Loan receivable bank"

    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 40
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
        saveData(textField)
    }
    func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
        saveData(textField)
        return true
    }

}



